<script setup lang="ts">
import { getMilstdList } from '@@/apis/resources/milstd';
import { getTaskTagApi } from "@@/apis/entity"
import { getModelList } from '@@/apis/resources/three-model';
import { BaseInfo } from '@@/apis/resources/types';
import { Search } from "@element-plus/icons-vue";
import { cloneDeep } from 'lodash';
import { computed, onMounted, nextTick, ref, watch } from 'vue';

interface Props {
  selected: BaseInfo | undefined
  type: "three-model" | "milstd"
  visible: boolean
}
const props = defineProps<Props>()
const emit = defineEmits(["closeDialog"])

const dialogVisible = ref<boolean>(false)
const btnLoading = ref<boolean>(false)
const loading = ref<boolean>(false)
const searchKey = ref<string>()
const searchTag = ref<string[]>([])
// const tags = ref<string[]>([])
const todoList = ref<BaseInfo[]>([])
const curItem = ref<BaseInfo | undefined>()
const pageNum = ref<number>(1)
const pageSize = ref<number>(3)
const tagList = ref<string[]>([])
const refresh = ref(false)
const total = ref<number>(0)

const disabled = computed(() => refresh.value || loading.value || noMore.value)
const noMore = computed(() => todoList.value.length >= total.value)

const handleSearch = () => {
  pageNum.value = 1
  todoList.value = []
  searchKey.value = searchKey.value
  getTableData()
}

const getTableData = () => {
  loading.value = true
  return new Promise((resolve) => {
    const api = props.type == 'milstd' ? getMilstdList : getModelList
    api({
      searchKey: searchKey.value,
      tags: searchTag.value,
      current: pageNum.value,
      pageSize: pageSize.value
    }).then(({ data }) => {
      todoList.value = todoList.value.concat(data.rows)
      pageNum.value += 1
      total.value = data.total
    }).finally(() => {
      loading.value = false
      resolve(true)
    })
  })
}
const moduleType = ref<string>('')
const getTaskTag = () => {
  getTaskTagApi({ module: moduleType.value })
    .then((res: any) => {
      tagList.value = res.data
    })
    .catch((e) => {
    })
}
const load = async () => {
  // 防止重复加载
  if (refresh.value) {
    return
  }
  await getTableData()
}

function refreshInfiniteList() {
  refresh.value = true
  todoList.value.length = 0
  nextTick(() => {
    refresh.value = false
    pageNum.value = 1
    load()
  })
}

const showDialog = () => {
  loading.value = true
  todoList.value = []
  refreshInfiniteList()
}

const closeDialog = () => {
  emit("closeDialog")
}
const handleConfirm = () => {
  emit("closeDialog", curItem.value)
}
const handleSelect = (item: BaseInfo) => {
  curItem.value = cloneDeep(item)
}
const handleTagClick = (item: any) => {
  const index: number = searchTag.value.indexOf(item.name)
  if (index == -1) {
    searchTag.value.push(item.name)
  } else {
    searchTag.value.splice(index, 1)
  }
  handleSearch()
}

watch(
  () => [props.selected, props.type, props.visible],
  () => {
    if (props.type == "milstd") {
      moduleType.value = 'gjb'
    } else {
      moduleType.value = '3dmodel'
    }
    getTaskTag()
    dialogVisible.value = props.visible
    curItem.value = cloneDeep(props.selected)
    if (props.visible) {
      showDialog()
    }
  }
)
</script>

<template>
  <el-drawer v-model="dialogVisible" direction="rtl" size="800" :append-to-body="true" @close-auto-focus="closeDialog"
    @close="closeDialog">
    <template #header>
      <h4>选择{{ type == "milstd" ? "军标" : "三维模型" }}</h4>
    </template>
    <template #default>
      <div class="cpi-header">
        <el-space class="cpi-header-tag">
          <el-tag v-for="(item, index) in tagList" :key="index"
            :class="(searchTag == undefined || searchTag?.indexOf(item.name) == -1) ? 'no-select' : ''" size="large"
            @click="handleTagClick(item)">{{ item.name }}</el-tag>
        </el-space>
        <el-input v-model="searchKey" placeholder="请输入搜索内容" style="width: 240px;">
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <el-space wrap direction="horizontal" style="width: 100%" :size="10" v-infinite-scroll="load"
        :infinite-scroll-disabled="disabled">
        <div v-for="(item, index) in todoList" :key="index" class="scenario-card"
          :class="curItem?.id == item.id ? 'selected' : ''" @click="handleSelect(item)">
          <div v-if="type == 'milstd'" class="container">
            <img :src="`/model-api${item.path}`" class="avatar" />
          </div>
          <div v-if="type == 'three-model'" ref="threeContainer" class="container three-container">
            <img :src="`/model-api${item.thumb}`" class="avatar" :title="item.thumb ? item.thumb : '暂无缩略图。。。'"/>
          </div>
          <div class="name" :title="item.name">{{ item.name }}</div>
        </div>
      </el-space>
      <p v-if="loading" style="color: #333;">Loading...</p>
      <p v-if="noMore" style="color: rgbargba(0, 0, 0, 0.2); text-align: center;">已加载完</p>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button plain @click="closeDialog">取 消</el-button>
        <el-button :loading="btnLoading" type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<style lang="scss" scoped>
@import "@@/assets/styles/mixins.scss";

.cpi-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: var(--main-padding);
}

.scenario-card {
  width: 170px;
  display: flex;
  flex-direction: column;
  cursor: pointer;

  .container {
    width: 100%;
    height: 170px;
    background: rgba(255, 255, 255, 0.1);
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 4px;

    .avatar {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }

  .name {
    color: #fff;
    text-align: center;
    line-height: 32px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  &.selected {
    .container {
      border: 4px solid #3a8dff;
    }
  }
}

.cpi-header-tag {
  .el-tag {
    cursor: pointer;
  }
}

.no-select {
  border: 1px solid transparent !important;
  color: #B1B1B1;
  background-color: transparent;
  font-size: 14px;
  cursor: pointer;
}
</style>
